package com.itheima.controller;

import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.itheima.common.R;
import com.itheima.properties.OssProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author Administrator
 */
@RestController
@RequestMapping("common")
public class CommonController {



    @Autowired
    private OssProperties ossProperties;


    @PostMapping(value = "/upload",produces = "application/json;charset=utf-8")
    public R<String> upload(MultipartFile file)throws IOException {

        String filename = file.getOriginalFilename();
        String suffixName = filename.substring(filename.lastIndexOf("."));

        String pathName = "D:/darkhorse/picture/";
        String pathNameHead = "file:///";
        String newFilename = UUID.randomUUID().toString().replaceAll("-","") + suffixName;

        File newFile = new File(pathName + newFilename);

        if (!newFile.getParentFile().exists()){
            newFile.getParentFile().mkdirs();
        }

        InputStream is = file.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(newFile));

        int len;
        byte[] bytes = new byte[1024];
        while ((len = bis.read(bytes))!=-1){
            bos.write(bytes,0,len);
        }
        bis.close();
        bos.close();

        return R.success(pathNameHead + pathName + newFilename);
    }

    // @PostMapping("upload")
    // public R<String> image(MultipartFile file) throws IOException {
    //
    //     String contentType = file.getContentType();
    //     if(StrUtil.isEmpty(contentType)){
    //         return R.error("文件缺失");
    //     }
    //
    //     //uuid重新生成文件名，防止文件名称重复而造成文件覆盖
    //
    //     String fileName = new SimpleDateFormat("yyyy-MM-dd").format(new Date())
    //             + "/" + UUID.randomUUID().toString() + "." + contentType.split("/")[1];
    //
    //     OSS ossClient = new OSSClientBuilder().build(ossProperties.getEndpoint(),
    //                                              ossProperties.getAccessKey(),
    //                                              ossProperties.getSecret());
    //        ossClient.putObject(ossProperties.getBucketName(),fileName,file.getInputStream());
    //
    //        ossClient.shutdown();
    //
    //        return R.success(ossProperties.getUrl()+"/"+fileName);
    // }

}
